# -*- coding: utf-8 -*-

import pickle

from hlm.node import *
from hlm.ui import ui_cprint, UIColor

from ip.fabrics import ChannelTranOpFabric, ChannelExecOpFabric

from hla.hla import hla_assemble_to_struct


class NodeOpDispatcher(Node):
    def initialize(self, params: ObjectDict) -> None:
        params.compile: bool
        params.filepath: str
        params.visual: bool
        if params.compile:
            # Need to compile the code
            import time
            start = time.clock()
            self.reg.nano_ops = hla_assemble_to_struct(params.filepath + '.py')
            elapsed = (time.clock() - start)
            print("Compiled finished, time used:", elapsed)
        else:
            # Load binary file directly from file.
            self.reg.nano_ops = pickle.load(open(params.filepath + '.p', 'rb'))
        # Prepare the ports for E-Runner and T-Runner.
        self.port.top_sender = self.port_channel_sender(ChannelTranOpFabric)
        self.port.eop_sender = self.port_channel_sender(ChannelExecOpFabric)
        # Create the pointer of each OPs.
        self.reg.top_pointer = 0
        self.reg.eop_pointer = 0
        self.reg.visual = params.visual

    def aops(self):
        return self.reg.nano_ops['aops']

    tasks = ['task_dispatch']

    def task_dispatch(self):
        # Check port states, send the data.
        if not self.port.top_sender.Bus.is_any_full() and \
                self.reg.top_pointer < len(self.reg.nano_ops['tops']):
            self.port.top_sender.Bus.put(nano_op=self.reg.nano_ops['tops'][self.reg.top_pointer])
            self.reg.top_pointer += 1
            if self.reg.visual:
                ui_cprint(UIColor.BLUE, '> Issued T-OP ...')

        if not self.port.eop_sender.Bus.is_any_full() and \
                self.reg.eop_pointer < len(self.reg.nano_ops['eops']):
            self.port.eop_sender.Bus.put(nano_op=self.reg.nano_ops['eops'][self.reg.eop_pointer])
            self.reg.eop_pointer += 1
            if self.reg.visual:
                ui_cprint(UIColor.BLUE, '> Issued E-OP ...')
